import { showFullScreenLoading, tryHideFullScreenLoading } from '@/api/axiosInitHelper'
let maxConnectAttempts = 5; // 最大连接尝试次数  
let connectAttempts = 0; // 当前连接尝试次数  
let currentConnectionTime = 1000; // 当前连接时间，单位：毫秒  
/* websocket实例 */
/**
* @param {Object} 
* path路径, tip提示, loading加载, onOpenCb打开的回调
* @return {*}    
*/
export const createWebsocketInstance = (path, tip, loading, onOpenCb) => {
  let websock = null
  let global_callback = null
  //数据接收
  let websocketonmessage = e => {
    global_callback(JSON.parse(e.data))
  }
  //发送消息
  let websocketsend = params => {
    websock.send(JSON.stringify(params))
  }
  //发送消息
  let closeSock = () => {
    websock.close()
  }
  // ws 连接状态
  let connectStatus = false
  if (typeof WebSocket === 'undefined') {
    alert(tip)
  } else {
    //  ip= 'ws://106.37.174.123:8762/
    //path= 'netwatch2-alarmprocess/webSocket';
    websock = new WebSocket(path)
    websock.onmessage = e => {
      // console.log('ws==接收数据111', e)
      if (loading) {
        tryHideFullScreenLoading()
      }
      if (!e.data || e.data === 'heartbeat') return
      websocketonmessage(e)
    }
    websock.onopen = () => {
      connectStatus = true
      onOpenCb && onOpenCb(connectStatus)
      // console.log('ws==建立连接')
      if (loading) {
        showFullScreenLoading()
      }
    }
    websock.onerror = err => {
      connectStatus = false
      onOpenCb && onOpenCb(connectStatus)
      console.log('ws=连接失败', err)
      if (loading) {
        tryHideFullScreenLoading()
      }
    }
    websock.onclose = () => {
      // websock.close(); //离开路由之后断开websocket连接
      connectStatus = false
      onOpenCb && onOpenCb(connectStatus)
      // console.log('ws==关闭')
    }
  }
  // 实际调用的方法，callback接收回调值
  let sendSock = (params, callback) => {
    global_callback = callback
    if (websock.readyState === websock.OPEN) {
      //若是ws开启状态
      websocketsend(params)
    } else if (websock.readyState === websock.CONNECTING) {
      // 若是 正在开启状态，则等待1s后重新调用
      setTimeout(function () {
        sendSock(params, callback)
      }, 1000)
    } else {
      // 若未开启 ，则等待1s后重新调用
      setTimeout(function () {
        sendSock(params, callback)
      }, 1000)
    }
  }
  return { sendSock, closeSock }
}
